package com.pic.serviceimpl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.pic.dao.PicDao;
import com.pic.entity.ObjResults;
import com.pic.entity.Picture;
import com.pic.service.PicService;

@Service("picService")
public class PicServiceImpl implements PicService {
	@Autowired
	@Qualifier("picDao")
	private PicDao picDao;

	/**
	 * 获取图片
	 */
	public void savePic() {
		picDao.savePic();

	}

	/**
	 * 将图片保存本地和数据库
	 */
	@Override
	public ObjResults saveFiles(List<MultipartFile> files) {
		List<Picture> list = savePicInfo(files);
		for (int i = 0; i <files.size() ;i++) {
			MultipartFile imgFile =files.get(i);
			Picture pic=list.get(i);
			saveWebImgFile(imgFile, pic);
		}
		ObjResults result = new ObjResults(list, "上传成功", "success");
		return result;
	}

	/**
	 * 保存数据库并返回pic list信息
	 * @param files
	 * @return
	 */
	private List<Picture> savePicInfo(List<MultipartFile> files) {
		List<Picture> list = new ArrayList<>();
		for (MultipartFile file : files) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			SimpleDateFormat sdf2 = new SimpleDateFormat("HHmmssSSS");
			String datePath = sdf.format(new Date());
			String datePath2 = sdf2.format(new Date());
			String dirPath = "/upload/img/" + datePath;
			File dir = new File(dirPath);
			if (!dir.exists()) {
				dir.mkdirs();
				dir.setWritable(true);
			}
			String fileName = datePath2 + file.getOriginalFilename();
			String filePath = dirPath + "/" + "b" + fileName;
			String midPath = dirPath + "/" + "m" + fileName;
			String smallPath = dirPath + "/" + "s" + fileName;
			Picture pic = new Picture();
			pic.setBigImg(filePath);
			pic.setMidImg(midPath);
			pic.setSmaImg(smallPath);
			pic.setFileSize(file.getSize());
			pic.setFileName(fileName);
			picDao.save(pic);
			list.add(pic);
		}
		return list;
	}

	/**
	 * 保存图片
	 * @param imgFile
	 * @return
	 */
	public void saveWebImgFile(MultipartFile imgFile,Picture pic) {
		if (imgFile.getSize() > 0) {
			FileOutputStream fos = null;
			try {
				byte[] b = imgFile.getBytes();
				File file = new File(pic.getBigImg());
				file.setWritable(true);
				fos = new FileOutputStream(file);
				fos.write(b);
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException("文件上传失败！", e);
			} finally {
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
						throw new RuntimeException("文件上传->输出流关闭失败！！！！", e);
					}
				}
			}
		}
	}
}
